package ch09
{
	import flash.display.Sprite;
	import flash.events.Event;

	import utils.Ball;

	/**
	 * 碰撞检测两个影片.
	 * 使用hitTestObject测试，圆形有问题.就会出现物体悬浮在空中的情景。
	 * 圆形测试
	 * @author sjp
	 *
	 */
	public class Balles extends Sprite
	{
		private var ball:Ball;
		private var balles:Array;
		private var gravity:Number=0.2;

		public function Balles()
		{
			init();
		}

		private function init():void
		{
			balles=new Array();
			createBall();
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onEnterFrame(event:Event):void
		{
			ball.vy+=gravity;
			ball.y+=ball.vy;
			if (ball.y + ball.height > stage.stageHeight)
			{
				ball.y=stage.stageHeight - ball.height / 2;
				createBall();
			}
			for (var i:uint=0; i < balles.length; i++)
			{
				if (ball != balles[i] && ball.hitTestObject(balles[i]))
				{
					ball.y=balles[i].y - balles[i].height / 2 - ball.height / 2;
					createBall();
				}
			}
		}

		private function createBall():void
		{
			ball=new Ball(Math.random() * 40 + 10, 0xFF0000);
			ball.x=Math.random() * stage.stageWidth;
			addChild(ball);
			balles.push(ball);
		}
	}
}